const {app, BrowserWindow, Tray, Menu, screen} = require("electron");

const path = require('path');

const NODE_ENV = process.env.NODE_ENV;

let mainWindow;

let cmd = require('node-cmd');

const isDevelopment = process.env.NODE_ENV !== 'production';  // true / false

async function createWindow() {
    const size = screen.getPrimaryDisplay().workAreaSize;  // 获取当前显示器屏幕宽高 不能使用{ width, height}来直接获取
    mainWindow = new BrowserWindow({
        width: size.width * 0.7,
        minWidth: 500,  // 固定值有效
        height: size.height * 0.5,
        minHeight: 550,  // 固定值有效

        webPreferences: {
            nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
            contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
            webSecurity: false,  // 允许跨域请求
            preload: path.join(__dirname, 'preload.js')  // 预加载的js文件
        }
    });

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
        if (!process.env.IS_TEST){
            mainWindow.webContents.openDevTools();
        }
    } else {
        await mainWindow.loadURL(
            NODE_ENV === 'development' ?
                'http://localhost:5173/' :  // 开发调试加载路径
                `file://${path.join(__dirname, '../dist/index.html')}`  // 打包后的加载路径
        );  // 加载网站

    }


    if (NODE_ENV === 'development') {
        mainWindow.webContents.openDevTools();  // 开发模式使用窗口调试
    }
}

let tray;

const isMac = process.platform === 'darmin';

const sendMenuEvent = async (url) => {
    await mainWindow.webContents.loadURL(url);
};

const templateMenu = [
    ...(isMac ? [{
        label: app.name,
        submenu: [
            {role: 'about'},
            {role: 'separator'},
            {role: 'services'},
            {role: 'separator'},
            {role: 'hide'},
            {role: 'hideothers'},
            {role: 'separator'},
            {role: 'quit'},
        ]
    }] : []),
    {
        label: '文件',
        submenu: [
            isMac ? {
                role: 'close',
                label: '退出',
            } : {
                role: 'quit',
                label: '退出'
            }
        ]
    },
    {
        label: '编辑',
        submenu: [
            {role: 'undo', label: '撤销'},
            {role: 'redo', label: '重置'},
            {type: 'separator'},
            {role: 'cut', label: '剪切'},
            {role: 'copy', label: '复制'},
            {role: 'paste', label: '粘贴'},
            ...(
                isMac ? [
                    {role: 'pasteAndMatchStyle'},
                    {role: 'delete', label: '删除'},
                    {role: 'selectAll', label: '全选'},
                    {type: 'separator'},
                    {
                        label: '搜索',
                        submenu: [
                            {role: 'startSpeaking'},
                            {role: 'stopSpeaking'},
                        ]
                    }
                ] : [
                    {role: 'delete', label: '删除'},
                    {type: 'separator'},
                    {role: 'selectAll', label: '全选'},
                ]
            )
        ]
    },
    {
        label: '视图',
        submenu: [
            {role: 'reload', label: '重新加载'},
            {role: 'forceReload', label: '强制重新加载'},
            {role: 'toggleDevTools', label: '调试工具'},
            {type: 'separator'},
            {role: 'resetZoom', label: '重置窗口'},
            {role: 'zoomIn', label: '放大'},
            {role: 'zoomOut', label: '缩小'},
            {type: 'separator'},
            {role: 'togglefullscreen', label: '全屏'}
        ]
    },
    {
        label: '窗口',
        submenu: [
            {role: 'minimize', label: '最小化'},
            {role: 'zoom', label: '缩放'},
            ...(
                isMac ? [
                    {type: 'separator'},
                    {role: 'front', label: '前置'},
                    {type: 'separator'},
                    {role: 'window', label: '窗口'},
                ] : [
                    {role: 'close', label: '退出'}
                ]
            )
        ]
    },
    {
        label: '帮助',
        role: 'help',
        submenu: [
            {
                label: 'doc文档(本地窗口)',
                role: 'help',
                accelerator: 'F1',
                click() {
                    sendMenuEvent('https://www.bilibili.com/');
                }
            },
            {
                label: 'doc文档(浏览器)',
                click: async () => {
                    const {shell} = require('electron');
                    await shell.openExternal('https://www.electronjs.org/zh/docs/latest/');
                }
            }
        ]
    }
];

const toolsMenu = Menu.buildFromTemplate(templateMenu);
Menu.setApplicationMenu(toolsMenu);  // 设置工具栏的菜单 / 汉化等

async function createMenuBar() {
    tray = new Tray('psyduck.ico');
    const contextMenu = Menu.buildFromTemplate([
        {
            role: 'togglefullscreen',
            label: '全屏',
            click: () => {
                mainWindow.setFullScreen(mainWindow.isFullScreen() !== true);
            }
        },
        {
            role: 'quit',
            label: '退出',
            click: () => {
                app.quit();
            }
        }
    ]);
    tray.setToolTip(app.name);  // 鼠标悬浮提示信息
    tray.on('right-click', () => {
        tray.popUpContextMenu(contextMenu);
    });  // 鼠标右键打开菜单内容
    tray.on('click', (e, bounds) => {
        mainWindow.show();
    });  // 单击展示窗口
}

async function createFlaskExe() {
    cmd.run(`start ` + path.join(__dirname, 'app/app.exe'), function (err, data, stderr) {
        console.log(data);
        console.log(err);
        console.log(stderr);
    });
}

app.on('ready', async () => {

    console.log("now start service");
    console.log(path.join(__dirname, 'app/app.exe'));

    // await createFlaskExe();  // 启动服务器exe

    await createWindow();  // 初始化窗口

    await createMenuBar();  // 初始化菜单栏
});

app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) {
        let result = createWindow();
    }
});  // 如果没有在活的窗口则打开一个窗口

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') {

        app.quit();

        cmd.run(`taskkill /F /im app.exe`);

    }
});  // 关闭窗口同时结束进程

if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit();
                // 关闭服务器exe
                cmd.run(`taskkill /F /im app.exe`);
            }
        });
    } else {
        process.on('SIGTERM', () => {
            app.quit();
            cmd.run(`taskkill /F /im app.exe`);
        });
    }
}